import random
import tkinter as tk
from tkinter import messagebox

def generate_random_numbers():
    """生成6个随机无序数字"""
    return random.sample(range(1, 100), 6)

def bubble_sort_step(numbers):
    """执行一轮冒泡排序，返回排序后的列表和交换信息"""
    n = len(numbers)
    swapped = False
    for i in range(n - 1):
        if numbers[i] > numbers[i + 1]:
            numbers[i], numbers[i + 1] = numbers[i + 1], numbers[i]
            swapped = True
    return numbers, swapped

class BubbleSortApp:
    def __init__(self, root):
        self.root = root
        self.root.title("冒泡排序轮巡填空")
        self.numbers = generate_random_numbers()
        self.rounds = []
        self.current_round = 0

        # 初始化每一轮的结果
        current_numbers = self.numbers.copy()
        for _ in range(len(self.numbers) - 1):
            current_numbers, swapped = bubble_sort_step(current_numbers)
            self.rounds.append(current_numbers.copy())
            if not swapped:
                break

        # 创建界面
        self.create_widgets()

    def create_widgets(self):
        """创建界面组件"""
        # 第一行：初始随机数字
        tk.Label(self.root, text="第一行（初始随机数字）：", font=("Arial", 12)).grid(row=0, column=0, columnspan=6)
        self.initial_label = tk.Label(self.root, text=self.format_numbers(self.numbers), font=("Arial", 12))
        self.initial_label.grid(row=1, column=0, columnspan=6)

        # 第二行：第一轮结果（自动填充）
        tk.Label(self.root, text="第一轮结果（自动填充）：", font=("Arial", 12)).grid(row=2, column=0, columnspan=6)
        self.auto_fill_label = tk.Label(self.root, text="", font=("Arial", 12))
        self.auto_fill_label.grid(row=3, column=0, columnspan=6)

        # 第三行及以后：用户填写每一轮结果
        self.user_input_entries = []
        for i in range(len(self.rounds)):
            tk.Label(self.root, text=f"第 {i + 1} 轮结果（用户填写）：", font=("Arial", 12)).grid(row=4 + i * 2, column=0, columnspan=6)
            entries_row = []
            for j in range(6):
                entry = tk.Entry(self.root, width=5, font=("Arial", 12))
                entry.grid(row=5 + i * 2, column=j)
                entries_row.append(entry)
            self.user_input_entries.append(entries_row)

        # 提交按钮
        self.submit_button = tk.Button(self.root, text="提交", command=self.check_answer, font=("Arial", 12))
        self.submit_button.grid(row=4 + len(self.rounds) * 2, column=0, columnspan=6)

        # 显示第一轮自动填充结果
        self.update_auto_fill()

    def format_numbers(self, numbers):
        """格式化数字显示"""
        return " ".join(f"[{num:2}]" for num in numbers)

    def update_auto_fill(self):
        """更新自动填充的结果"""
        if self.current_round < len(self.rounds):
            self.auto_fill_label.config(text=self.format_numbers(self.rounds[self.current_round]))
        else:
            self.auto_fill_label.config(text="排序完成！")

    def check_answer(self):
        """检查用户输入是否正确"""
        if self.current_round >= len(self.rounds):
            messagebox.showinfo("提示", "排序已完成！")
            return

        user_numbers = []
        for entry in self.user_input_entries[self.current_round]:
            try:
                num = int(entry.get())
                user_numbers.append(num)
            except ValueError:
                messagebox.showerror("错误", "请输入有效的数字！")
                return

        if user_numbers == self.rounds[self.current_round]:
            messagebox.showinfo("正确", "填写正确！")
            self.current_round += 1
            self.update_auto_fill()
        else:
            messagebox.showerror("错误", "填写错误，请重试！")

if __name__ == "__main__":
    root = tk.Tk()
    app = BubbleSortApp(root)
    root.mainloop()